#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void MergeSortNonR(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	int gap = 1;
	
	while (gap < n)
	{
	    int i = 0;
		for (i = 0; i < n; i += 2 * gap)
		{
			int begin1 = i; int end1 = i + gap - 1;
			int begin2 = i + gap; int end2 = i + 2 * gap - 1;
			int index = begin1; 
			if (begin2 >= n)
			{
				break;
			}
			if (end2 >= n)
			{
				end2 = n - 1;
			}
			int num = end2 - begin1 + 1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] <= a[begin2])
				{
					tmp[index++] = a[begin1++];
				}
				else
				{
					tmp[index++] = a[begin2++];
				}
			}
			while (begin1 <= end1)
			{
				tmp[index++] = a[begin1++];
			}
			while (begin2 <= end2)
			{
				tmp[index++] = a[begin2++];
			}
			memcpy(a + i, tmp + i, sizeof(int) * num);
		}
		gap *= 2;
	}
	free(tmp);
}
void CountSort(int *arr,int n)
{
	int i = 0; int max = arr[0]; int min = arr[0];
	for (i = 0; i < n; i++)
	{
		if (max < arr[i])
		{
			max = arr[i];
		}
		if (min > arr[i])
		{
			min = arr[i];
		}
	}
	int length = max - min+1;
	int* tmp = calloc(length, sizeof(int));
	for (i = 0; i < n; i++)
	{
		tmp[arr[i]-min]++;
	}
	int j = 0;
	for (j = 0, i = 0; j < n; i++)
	{
		while (tmp[i] > 0)
		{
			arr[j++] = i+min;
			tmp[i]--;
		}
	}
}
void printf_arr(int* arr, int n)
{
	int i = 0;
	for(i = 0; i < n; i++)
	printf("%d ", arr[i]);
	printf("\n");
}
int main()
{
	int arr[] = { 9,8,7,6,4,3,2,1};
	int sz = sizeof(arr) / sizeof(int);
	//MergeSortNonR(arr, sz);
	CountSort(arr, sz);
	printf_arr(arr, sz);
}